package com.hongyun.tms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.hongyun.tms.common.PageResponseDto;
import com.hongyun.tms.common.constants.DefaultCreateByConstant;
import com.hongyun.tms.common.dto.tug.SelecSearchDTO;
import com.hongyun.tms.common.dto.tug.TmsMTugQueryDto;
import com.hongyun.tms.common.dto.tug.TmsMTugSaveReqDto;
import com.hongyun.tms.common.enums.BizCode;
import com.hongyun.tms.common.utils.MapperingUtils;
import com.hongyun.tms.common.vo.TmsMTugVO;
import com.hongyun.tms.entity.PordWork;
import com.hongyun.tms.entity.TmsMTug;
import com.hongyun.tms.exception.BusinessRuntimeException;
import com.hongyun.tms.mapper.TmsMTugMapper;
import com.hongyun.tms.service.IPordWorkService;
import com.hongyun.tms.service.TmsMTugService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 拖轮信息表
 *
 * @author yuheng
 * @since 1.0.0 2024-06-06
 */
@Service
public class TmsMTugServiceImpl extends ServiceImpl<TmsMTugMapper, TmsMTug> implements TmsMTugService {

    @Resource
    private IPordWorkService workService;

    @Override
    public PageResponseDto<TmsMTugVO> page(TmsMTugQueryDto query) {
        Page<TmsMTug> page = new Page<>(query.getStartPage(), query.getPageSize());
         baseMapper.selectPage(page, getWrapper(query));
        PageResponseDto<TmsMTugVO> voPage = new PageResponseDto(page, TmsMTugVO.class);
        return voPage;
    }

    private LambdaQueryWrapper<TmsMTug> getWrapper(TmsMTugQueryDto query) {
        LambdaQueryWrapper<TmsMTug> wrapper = Wrappers.lambdaQuery();
        wrapper.like(StringUtils.isNotBlank(query.getTugName()), TmsMTug::getTugName, query.getTugName())
                .like(StringUtils.isNotBlank(query.getTugNo()), TmsMTug::getTugNo, query.getTugNo())
                .like(StringUtils.isNotBlank(query.getCallNo()), TmsMTug::getCallNo, query.getCallNo())
                .eq(query.getStaus() != null, TmsMTug::getStaus, query.getStaus())
                .eq(StringUtils.isNotBlank(query.getTugTypeCode()), TmsMTug::getTugTypeCode, query.getTugTypeCode())
                .eq(StringUtils.isNotBlank(query.getPortAreaCode()), TmsMTug::getPortAreaCode, query.getPortAreaCode())
                .orderByDesc(TmsMTug::getUpdateTime);
        return wrapper;
    }

    @Override
    public void save(TmsMTugSaveReqDto dto) {
        TmsMTug entity = MapperingUtils.copyProperties(dto, TmsMTug.class);
        if (entity != null) {
            entity.setId(IdWorker.getId());
            entity.setCreateTime(LocalDateTime.now());
            entity.setCreateBy(DefaultCreateByConstant.userId);
            entity.setCreateByName(DefaultCreateByConstant.userId.toString());
            entity.setUpdateTime(LocalDateTime.now());
            entity.setUpdateByName(DefaultCreateByConstant.userId.toString());
            entity.setUpdateBy(DefaultCreateByConstant.userId);
            baseMapper.insert(entity);
        }
    }

    @Override
    public void update(TmsMTugSaveReqDto dto) {
        TmsMTug entity = MapperingUtils.copyProperties(dto, TmsMTug.class);
        entity.setUpdateTime(LocalDateTime.now());
        entity.setUpdateBy(DefaultCreateByConstant.userId);
        entity.setUpdateByName(DefaultCreateByConstant.userId.toString());
        updateById(entity);
    }

    @Override
    public List<Map<String, Object>> getTugList(SelecSearchDTO selectCommonSearch) {
        return baseMapper.getTugList(selectCommonSearch);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(String ids) {
        String[] split = ids.split(",");
        List<String> tugIdList = Arrays.asList(split);
        //如果被引用了则无法删除
        referenceCheck(tugIdList);

        removeByIds(tugIdList);
    }

    private void referenceCheck(List<String> tugIdList) {
        //pord work tugId检查
        long workCount = workService.count(new LambdaQueryWrapper<PordWork>().in(PordWork::getTugId, tugIdList));
        if (workCount > 0) {
            throw new BusinessRuntimeException(BizCode.DELETE_FAILED, "该拖轮被【拖轮作业记录】引用，无法删除");
        }

    }

    @Override
    public List<TmsMTugVO> export(TmsMTugQueryDto query) {
        long currentPage = 1;
        List<TmsMTugVO> allRecords = Lists.newArrayList();

        while (true) {
            query.setStartPage(currentPage);
            PageResponseDto<TmsMTugVO> page = this.page(query);
            List<TmsMTugVO> records = page.getRecords();
            allRecords.addAll(records);

            if (records.size() < query.getPageSize()) {
                // 当前页的记录数小于 pageSize，说明已经是最后一页
                break;
            }
            currentPage++;
        }

        return allRecords;
    }
}
